package il.technion.cs236369.webserver;

import il.technion.cs236369.webserver.typeHandlers.Session;

import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

public class SessionManager
{
	private static HashMap<Integer, Session> sessions = new HashMap<Integer, Session>();
	private static Integer idCounter = 0;

	public static Integer initiateSession(ExtendedHttpRequest request, HttpResponse response)
	{
		Integer id;
		Header cookieHeader = request.getHttpRequest().getFirstHeader("Cookie");

		if (cookieHeader != null) 
		{
			String cookie = cookieHeader.getValue();
			boolean matches = cookie.matches("(.*id=([0-9]+).*)");
			if (matches)
			{
				id = Integer.parseInt(cookie.substring(3));
			} else
			{
				id = null;
			}

			synchronized (sessions)
			{
				if (id != null && sessions.get(id) != null)
				{
					return id;
				}
			}
		}

		synchronized (sessions)
		{
			id = ++idCounter;
			sessions.put(id, new Session());
		}

		return id;
	}

	public static Session getSession(Integer id)
	{
		synchronized (sessions)
		{
			return sessions.get(id);
		}
	}

	public static void invalidateSession(Integer id)
	{
		getSession(id).invalidate();
		synchronized (sessions)
		{
			sessions.remove(id);
		}
	}

}
